import sensor, image, time

# 摄像头初始化
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_vflip(True)  # 根据安装方向调整
sensor.set_hmirror(True)  # 根据安装方向调整
sensor.skip_frames(time=2000)

# 加载人脸检测模型
face_cascade = image.HaarCascade("frontalface", stages=25)

# 颜色阈值（可根据实际环境调整）
red_threshold = (30, 60, 20, 60, 10, 40)

# 性能优化：预分配内存缓冲区
img_buf = sensor.alloc_extra_fb(sensor.width(), sensor.height(), sensor.RGB565)

clock = time.clock()

while True:
    clock.tick()
    img = sensor.snapshot()
    
    # 人脸检测（优化参数）
    faces = img.find_features(face_cascade, threshold=0.75, scale_factor=1.2)
    for f in faces:
        img.draw_rectangle(f)
        img.draw_string(f[0], f[1], "Face", color=(255, 0, 0))
    
    # 颜色检测（优化参数）
    blobs = img.find_blobs([red_threshold], pixels_threshold=200, 
                          area_threshold=200, merge=True)
    for blob in blobs:
        img.draw_rectangle(blob.rect())
        img.draw_cross(blob.cx(), blob.cy())
        img.draw_string(blob.cx(), blob.cy(), "Red", color=(0, 255, 0))
    
    # 性能监控
    fps = clock.fps()
    img.draw_string(0, 0, f"FPS: {fps:.2f}", color=(255, 255, 255))
    print(f"FPS: {fps}")